<!--微信自定义菜单-->
<template>
  <div id="wechatMenu" class="app-container">
    <div class="flex-row">
      <div class="wechat-menu-container">
        <div class="weixin-hd">
          <div class="weixin-title">
            <el-form :model="listQuery" :inline="true">
              <el-form-item>
                <application-key-select ref="applicationKeySelect" v-model="listQuery.appId" :type="listQuery.type" />
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div class="weixin-menu  clearfix">
          <div v-for="firstItem in menuData" :key="firstItem.id" class="menu_bottom">
            <div class="menu_item el-icon-s-fold" @click="clickFirstMenu(firstItem)">{{ firstItem.name }}</div>
            <div v-show="activeMenuIndex===firstItem.id" class="submenu">
              <div v-for="secondItem in firstItem.children" :key="secondItem.id" class="subtitle menu_bottom">
                <div class="menu_subItem" @click="clickSecondMenu(secondItem)">{{ secondItem.name }}</div>
              </div>
              <div v-if="firstItem.children.length<5" class="menu_bottom"><i class="el-icon-plus" @click="clickAddSecondMenu(firstItem.id)" /></div>
            </div>
          </div>
          <div v-if="menuData.length<3" class="menu_bottom" @click="clickAddFirstMenu(0)"><i class="el-icon-plus" /></div>
        </div>
        <div class="save_div">
          <el-button v-if="menuRecord.name" type="primary" :loading="buttonLoading" @click="status==='create'?createData():updateData()">保存</el-button>
          <el-button v-if="menuData.length>0" type="primary" :loading="buttonLoading" @click="generalMenu">发布</el-button>

        </div>
      </div>
      <div class="wechat-menu-form-container">
        <template v-if="menuRecord.pid!=null">
          <div class="common-title m-b-20">
            <h2 class="bold">{{ menuRecord.name?menuRecord.name:'请设置标题' }}</h2>
            <el-link v-if="menuRecord.id" type="danger" :underline="false" @click="removeRecord(menuRecord)">删除菜单</el-link>
          </div>
          <div v-if="menuRecord.children" class="m-b-20 common-tips">
            已添加子菜单，仅可设置菜单名称。
          </div>
          <el-form ref="menuForm" :rules="rules" :model="menuRecord" label-position="right" label-width="120px">
            <el-form-item label="菜单名称:" prop="name">
              <el-input v-model="menuRecord.name" maxlength="8" show-word-limit placeholder="仅支持中英文和数字，字数不超过4个汉字或8个字母" />
            </el-form-item>
            <template v-if="!menuRecord.children || menuRecord.children.length===0">
              <el-form-item label="类型:" prop="type">
                <el-select v-model="menuRecord.type" placeholder="请选择" style="width:100%" @change="changeType">
                  <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item v-if="menuRecord.type==='view'" :label="menuRecordTypeLabel" prop="eventValue">
                <el-input v-model="menuRecord.eventValue" :disabled="menuRecord.type=='click'" :placeholder="'请输入'+menuRecordTypeLabel" />
              </el-form-item>
              <template v-if="menuRecord.type==='miniprogram'">
                <el-form-item label="小程序APPID" prop="mpAppId">
                  <el-input v-model="menuRecord.mpAppId" placeholder="请输入小程序APPID" maxlength="20" show-word-limit clearable />
                </el-form-item>
                <el-form-item label="小程序页面路径" prop="mpPagePath">
                  <el-input v-model="menuRecord.mpPagePath" placeholder="请输入小程序页面路径" maxlength="50" show-word-limit clearable />
                </el-form-item>
                <el-form-item label="小程序备用地址" prop="mpUrl">
                  <el-input v-model="menuRecord.mpUrl" placeholder="请输入小程序备用地址" maxlength="100" show-word-limit clearable />
                </el-form-item>
                <el-form-item>
                  <div class="color-danger">
                    tips:需要和公众号进行关联才可以把小程序绑定带微信菜单上哟！
                  </div>
                </el-form-item>

              </template>
            </template>
            <el-form-item v-if="menuRecord.type==='click'">
              <div class="color-danger">
                tips:先保存菜单，再进行设置消息回复！
              </div>
            </el-form-item>
            <el-form-item label="排序:" prop="orders">
              <el-input-number v-model="menuRecord.orders" placeholder="请输入排序" show-word-limit :max="99" style="width:100%" />
            </el-form-item>
            <el-form-item v-if="menuRecord.id && menuRecord.type==='click' && menuRecord.children.length===0" style="height: 400px; overflow: auto;">
              <material-selection ref="materialSelection" v-model="replyContent" :app-id="listQuery.appId" />
              <div style="text-align: center; padding-top: 50px;">
                <el-button type="primary" plain @click="handleWechatMenuReplySave">保存</el-button>
              </div>
            </el-form-item>

          </el-form>
        </template>
        <div v-else class="conmmon-container-main flex-main" style="background-color: #fff;text-align: center;padding-top: 15%;font-weight: bold;">
          请先选择菜单
        </div>
      </div>
    </div>
  </div>
</template>
<script>

import applicationKeySelect from '../applicationKeySelect'
import MaterialSelection from './components/materialSelection.vue'
export default {
  components: { applicationKeySelect, MaterialSelection },
  data() {
    return {
      wechatConfigRecords: {},
      listQuery: {
        appId: '',
        type: 1
      },
      activeMenuIndex: null,
      articleListQuery: {
        page: 1,
        limit: 10,
        sort: '-gmtModified',
        type: 1
      },
      typeOptions: [
        { value: 'click', label: '发送消息' },
        { value: 'view', label: '跳转网页' },
        { value: 'miniprogram', label: '小程序' }

      ],
      parentOptions: [],
      columns: [
        { text: '名称', dataIndex: 'name' },
        { text: '类型', dataIndex: 'type' },
        { text: '菜单值', dataIndex: 'eventValue' }
      ],
      menuData: [],
      status: 'create',
      buttonLoading: false,
      menuRecord: {
        children: []
      },
      menuRecordTypeLabel: 'Key',
      rules: {
        name: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
        type: [{ required: true, message: '请选择类型', trigger: 'blur' }],
        eventValue: [{ required: true, message: '请填写', trigger: 'blur' }],
        pid: [{ required: true, message: '请选择所属上级', trigger: 'blur' }],
        mpAppId: [{ required: true, message: '请输入小程序APPID', trigger: 'blur' }],
        mpPagePath: [{ required: true, message: '请输入小程序页面路径', trigger: 'blur' }]
      },
      replyContent: JSON.stringify({ })

    }
  },
  watch: {
    'listQuery.appId': function(val) {
      this.getWechatConfig()
      this.fetchData()
      this.replyContent = JSON.stringify({
        resourceType: 3,
        appId: this.listQuery.appId
      })
    }
  },
  created() {
  },
  methods: {
    async generalMenu() {
      try {
        await this.$store.dispatch('wechatMenuGenerate', this.listQuery.appId)
        this.$modal.msgSuccess('创建成功')
      } catch (err) {
        console.log(err)
      }
    },
    async getWechatConfig() {
      const response = await this.$store.dispatch('applicationKeyConfigGetByAppId', this.listQuery.appId)
      if (response == null) {
        this.$modal.msgWarning('请先配置相关信息！')
        return
      }
      this.wechatConfigRecords = response
    },
    async fetchData() {
      const response = await this.$store.dispatch('wechatMenuTreeTable', this.listQuery)
      this.menuData = response
    },
    clickFirstMenu(value) {
      this.activeMenuIndex = value.id
      this.menuRecord = Object.assign({}, value) // copy obj
      this.status = 'update'
      if (this.menuRecord.children.length === 0 && this.menuRecord.type === 'click') {
        this.fetchAutoReplyData(this.menuRecord.eventValue)
      }
    },
    clickSecondMenu(value) {
      this.menuRecord = Object.assign({}, value) // copy obj
      this.menuRecord = {
        ...this.menuRecord,
        children: []
      }
      this.status = 'update'
      if (this.menuRecord.type === 'click') {
        this.fetchAutoReplyData(this.menuRecord.eventValue)
      }
    },
    fetchAutoReplyData(key) {
      this.$store.dispatch('thirdWechatAutoReplyPage', {
        appId: this.listQuery.appId,
        relationConfigId: key,
        replayType: 3,
        page: 1,
        limit: 1
      }).then(response => {
        this.backShowValue(response.records.length > 0 ? response.records[0] : {})
      })
    },
    /**
     * 回显数据
     */
    backShowValue(jsonData) {
      var { resourceType, appId, id } = jsonData
      if (!id) {
        this.replyContent = JSON.stringify({
          resourceType: 3,
          appId: this.listQuery.appId
        })
        return
      }
      var replyContent = {
        id: id,
        resourceType: resourceType,
        appId: appId
      }
      if (resourceType === 3) {
        // 文本
        replyContent = {
          ...replyContent,
          textContent: jsonData.textContent
        }
      }
      if (resourceType === 0) {
        // 图片
        replyContent = {
          ...replyContent,
          title: jsonData.title,
          fileUrl: jsonData.fileUrl,
          mediaId: jsonData.mediaId
        }
      }
      if (resourceType === 1 || resourceType === 2) {
        // 音频、视频
        replyContent = {
          ...replyContent,
          title: jsonData.title,
          textContent: jsonData.textContent,
          mediaId: jsonData.mediaId
        }
      }
      if (resourceType === 4) {
        // 图文
        replyContent = {
          ...replyContent,
          articleContents: jsonData.articleContent ? JSON.parse(jsonData.articleContent) : []
        }
      }
      this.replyContent = JSON.stringify(replyContent)
    },
    clickAddFirstMenu(value) {
      this.menuRecord = { pid: value, name: '菜单名称', orders: 99 }
      this.status = 'create'
      this.$nextTick(() => {
        this.$refs['menuForm'].clearValidate()
      })
    },
    clickAddSecondMenu(value) {
      this.menuRecord = { pid: value, name: '子菜单名称', orders: 99 }
      this.status = 'create'
      this.$nextTick(() => {
        this.$refs['menuForm'].clearValidate()
      })
    },
    changeType() {
      if (this.menuRecord.type === 'view') {
        const menuRecord = Object.assign({}, this.menuRecord) // copy obj
        menuRecord.eventValue = ''
        this.menuRecord = menuRecord
        this.menuRecordTypeLabel = '跳转路径'
      }
      if (this.menuRecord.type === 'click') {
        const menuRecord = Object.assign({}, this.menuRecord) // copy obj
        menuRecord.eventValue = new Date().getTime() + ''
        this.menuRecord = menuRecord
        // this.menuRecord.eventValue = new Date().getTime() + "";
        this.menuRecordTypeLabel = 'Key'
      }
      if (this.menuRecord.type === 'miniprogram') {
        const menuRecord = Object.assign({}, this.menuRecord) // copy obj
        menuRecord.eventValue = new Date().getTime() + ''
        this.menuRecord = menuRecord
        this.menuRecordTypeLabel = 'Key'
      }
    },

    createData() {
      this.$refs['menuForm'].validate(valid => {
        if (valid) {
          this.menuRecord = {
            ...this.menuRecord,
            appId: this.listQuery.appId
          }
          this.$store.dispatch('wechatMenuSave', this.menuRecord).then(response => {
            this.$modal.msgSuccess('创建成功')
            this.handleFilter()
          }).catch(() => {
          })
        }
      })
    },

    updateData() {
      this.$refs['menuForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.menuRecord)
          delete tempData.children
          delete tempData._parent
          this.$store.dispatch('wechatMenuUpdate', tempData).then(response => {
            this.$modal.msgSuccess('修改成功')
            this.handleFilter()
          }).catch(() => {
          })
        }
      })
    },

    removeRecord(row) {
      const ids = [row.id]
      this.$confirm('此操作将永久删除记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('wechatMenuRemove', ids).then(response => {
          this.handleFilter()
          this.menuRecord = {}
          this.$modal.msgSuccess('删除成功!')
        }).catch(() => {})
      }).catch(() => {})
    },

    /**
     * 搜索
     */
    handleFilter() {
      this.listQuery.page = 1
      this.fetchData()
    },
    handleWechatMenuReplySave() {
      var value = this.$refs.materialSelection.getSelectValue()
      this.$store.dispatch('thirdWechatAutoReplySave', this.assignValue(value, this.menuRecord.eventValue)).then(response => {
        this.$modal.msgSuccess('配置成功!')
      }).catch(() => {
      })
    },
    /**
     * 组装选择的数据
     * @param {*} value
     */
    assignValue(value, key) {
      var { resourceType, appId } = value
      var record = {
        relationConfigId: key,
        replayType: 3,
        resourceType: resourceType,
        appId: appId
      }
      if (resourceType === 3) {
        // 文字
        record = {
          ...record,
          textContent: value.textContent
        }
      } else if (resourceType === 0) {
        // 图片
        record = {
          ...record,
          title: value.title,
          fileUrl: value.attachment,
          mediaId: value.mediaId
        }
      } else if (resourceType === 1 || resourceType === 2) {
        // 音频、视频
        record = {
          ...record,
          title: value.title,
          textContent: value.textContent,
          mediaId: value.mediaId
        }
      } else if (resourceType === 4) {
        // 图文
        record = {
          ...record,
          articleContent: JSON.stringify(value.articleContents)
        }
      }
      return record
    }
  }
}
</script>
<style lang="scss" >
#wechatMenu{
  background-color: #fff;
  padding: 20px;
  .wechat-menu-container{
    display: inline-block;
    width: 350px;
    height: 715px;
    background: url(~@/assets/images/iphone_backImg.png) no-repeat;
    background-size: 100% auto;
    padding: 518px 25px 88px;
    position: relative;
    box-sizing: border-box;
    .weixin-hd{
      color: #fff;
      text-align: center;
      position: relative;
      bottom: 426px;
      left: 0;
      width: 300px;
      height: 64px;
      background: transparent url(~@/assets/images/iphone_head.png) no-repeat 0 0;
      background-position: 0 0;
      background-size: 100%;
    }
    .weixin-title{

      width: 100%;
      text-align: center;
      position: absolute;
      top: 24px;
      left: 0;
      .el-form-item--mini.el-form-item, .el-form-item--small.el-form-item{
        margin-bottom: 0px;
      }
      .el-input__inner{
        background-color: #ffffff00;
        color: #fff;
        font-size: 14px;
        border: 0px;
      }
    }
    .weixin-menu {
      background: transparent url() no-repeat 0 0;
      padding-left: 43px;
      font-size: 12px;
      .menu_bottom {
        position: relative;
        display: inline-block;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
        width: 85.5px;
        height: inherit;
        line-height: 46px;
        text-align: center;
        border: 1px solid #ebedee;
        background-color: #fff;
        cursor: pointer;
      }
      .menu_item {
        height: 44px;
        line-height: 44px;
        text-align: center;
        box-sizing: border-box;
        width: 100%;
      }
      .menu_bottom:hover{
        background-color: #ecf5ff;
        border: 1px solid #ecf5ff;
      }
      .submenu {
        position: absolute;
        width: 85.5px;
        bottom: 45px;
      }

    }
    .save_div{
      margin-top: 15px;
      text-align: center;
    }
  }
  .wechat-menu-form-container{
    margin-left: 20px;
    flex: 1;
  }
}
</style>
